import os

import tornado
from tornado import web, ioloop


# 定义一个 uimodule
class OrderModule(web.UIModule):
    def cal_total(self, price, nums):
        return price * nums

    def render(self, order, *args, **kwargs):
        return self.render_string("ui_modules/order-list.html", order=order, cal_total=self.cal_total)

    # 直接写成字符串传递到页面中
    # def embedded_css(self):
    #     return "body{background-color:red}"
    # def embedded_javascript(self):
    #     return "alert('嵌入js代码')"

    # def css_files(self):
    #     return "ui_modules/order-list.css"
    # def javascript_files(self):
    #     return "ui_modules/order-list.js"


class MainHandler(web.RequestHandler):

    async def get(self, *args, **kwargs):
        self.write("hello world!")


class OrderHandler(web.RequestHandler):

    async def get(self, *args, **kwargs):
        orders = [
            {
                "name": "小米T恤 忍者米兔双截棍 军绿 XXL <b>这段文本加粗</b>",
                "image": "http://i1.mifile.cn/a1/T11lLgB5YT1RXrhCrK!40x40.jpg",
                "price": 39,
                "nums": 3
            },
            {
                "name": "招财猫米兔 白色",
                "image": "http://i1.mifile.cn/a1/T14BLvBKJT1RXrhCrK!40x40.jpg",
                "price": 49,
                "nums": 2
            },
            {
                "name": "小米圆领纯色T恤 男款 红色 XXL",
                "image": "http://i1.mifile.cn/a1/T1rrDgB4DT1RXrhCrK!40x40.jpg",
                "price": 59,
                "nums": 1
            },
        ]

        self.render('uimodule/order.html', orders=orders)


urls = [
    ("/", MainHandler),
    ("/order/?", OrderHandler)
]

if __name__ == '__main__':
    base_dir = os.path.dirname(__file__)
    setting = {
        # 设置静态文件路径，默认前缀是 static  => http://xxx.com/static/1.png
        "static_path": os.path.join(base_dir, 'static'),
        'static_url_prefix': "/static/",  # 设置静态文件路径前缀
        'template_path': os.path.join(base_dir, 'templates'),
        'ui_modules': {
            "OrderModule": OrderModule
        }
    }

    app = web.Application(urls, debug=False, **setting)
    app.listen(8000)

    ioloop.IOLoop.current().start()
